﻿using System;
using System.Net;
using System.ServiceModel.Syndication;
using System.Xml;

namespace Songhay.Net
{
    /// <summary>
    /// Static members for <see cref="System.Net.WebRequest"/>.
    /// </summary>
    public static partial class HttpVerbAsyncUtility
    {
        /// <summary>
        /// Gets the <see cref="System.ServiceModel.Syndication.SyndicationFeed"/>.
        /// </summary>
        /// <param name="resourceIndicator">The resource indicator.</param>
        /// <param name="getFeedCompleteAction">The get feed complete action.</param>
        public static void GetFeed(Uri resourceIndicator, Action<SyndicationFeed> getFeedCompleteAction)
        {
            if(getFeedCompleteAction == null)
                throw new ArgumentNullException("getFeedCompleteAction",
                    "The generic Action is null.");

            var action = new Action<object, OpenReadCompletedEventArgs>(
            (o, args) =>
            {
                if(args.Error != null)
                    throw new WebException("Problem getting file.", args.Error);
                var feed = GetFeed(args);
                getFeedCompleteAction.Invoke(feed);
            });

            HttpVerbAsyncUtility.GetStream(resourceIndicator, action);
        }

        /// <summary>
        /// Gets the <see cref="System.ServiceModel.Syndication.SyndicationFeed"/>.
        /// </summary>
        /// <param name="resourceIndicator">The resource indicator.</param>
        /// <param name="getFeedCompleteAction">The get feed complete action.</param>
        public static void GetFeed(Uri resourceIndicator,
            Action<SyndicationFeed, object, OpenReadCompletedEventArgs> getFeedCompleteAction)
        {
            if(getFeedCompleteAction == null)
                throw new ArgumentNullException("getFeedCompleteAction", "The generic Action is null.");

            var action = new Action<object, OpenReadCompletedEventArgs>(
            (o, args) =>
            {
                if(args.Error != null) return;
                var feed = GetFeed(args);
                getFeedCompleteAction.Invoke(feed, o, args);
            });

            HttpVerbAsyncUtility.GetStream(resourceIndicator, action);
        }

        static SyndicationFeed GetFeed(OpenReadCompletedEventArgs args)
        {
            SyndicationFeed feed = null;
            var reader = XmlReader.Create(args.Result);
            feed = SyndicationFeed.Load(reader);
            return feed;
        }
    }
}
